<?php

namespace common\models\app;

use Yii;
use common\helpers\Url;

/**
 * This is the model class for table "{{%app_version}}".
 *
 * @property int $id
 * @property string $admin_id 发布人ID
 * @property string $os 操作系统
 * @property string $build build版本序列号
 * @property string $version 版本号
 * @property string $sign APK文件签名md5值
 * @property string $link 下载地址
 * @property string $explain 版本升级说明
 * @property int $status 版本发布状态
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at 删除时间
 */
class AppVersion extends \common\base\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;
    use \common\traits\QueryInstanceActiveRecord;

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    //
    const STATUS_TEST = 1;
    const STATUS_DEV = 2;
    //
    const STATUS_PROD = 10;
    const STATUS_END = 20;
    //
    const OS_MP = 'mp';
    const OS_ANDROID = 'android';
    const OS_IOS = 'ios';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%app_version}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['admin_id', 'build', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['os'], 'string'],
            [['version'], 'required'],
            [['version'], 'string', 'max' => 11],
            [['sign'], 'string', 'max' => 32],
            [['link', 'explain'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'admin_id' => '发布人ID',
            'os' => '操作系统',
            'build' => 'build版本序列号',
            'version' => '版本号',
            'sign' => 'APK文件签名md5值',
            'link' => '下载地址',
            'explain' => '版本升级说明',
            'status' => '版本发布状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public static function getLatest($os = 'android') {
        return static::find()->where([
            'os' => $os,
            'status' => static::STATUS_PROD
        ])
        ->orderBy(['build' => SORT_DESC])
        ->cache(600)
        ->one();
    }

    public function fields() {
        return [
            'id',
            'os',
            'build',
            'version',
            'link' => function() {
                return Url::toRemote($this->link);
            },
            'explain',
            'force' => function() {
                return true;
            },
            'release_time' => function() {
                return date('Y-m-d H:i', $this->created_at);
            },
        ];
    }

}
